package web.controller.common;

import common.consts.ContentType;
import common.validation.ValidationResult;
import domain.UserLocation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import service.ServiceResponse;
import service.UserLocationService;
import web.Routes;
import web.controller.Base;
import web.req.GeoRequest;
import web.security.Protection;

/**
 * Created by aceyin on 15/7/9.
 */
@RestController
@RequestMapping(Routes.Common.GEO)
public class Geo extends Base {

    @Autowired
    private UserLocationService userLocationService;

    /**
     * 获取用户地理位置信息
     *
     * @return
     */
    @Protection
    @RequestMapping(method = RequestMethod.GET, produces = ContentType.JSON)
    public ServiceResponse get() {
        long userid = getUserIdFromAuthHeader();
        return userLocationService.get(userid);
    }

    /**
     * 更新用户地理位置信息
     *
     * @return
     */
    @Protection
    @RequestMapping(method = RequestMethod.POST, produces = ContentType.JSON)
    public ServiceResponse update(@RequestBody GeoRequest request) {
        ValidationResult result = request.validate();
        if (result.isFailed()) {
            return fail(result.getMessage());
        }

        long userId = getUserIdFromAuthHeader();

        UserLocation location = copy(request, UserLocation.class);

        return userLocationService.update(userId, location);
    }
}
